<template>
  <div class="pageContent">
    <div class="centerAll">
      <Table ref="xrTable" :list-api="list" :status-api="status" :table-column="tableColumn" :page-config="pageConfig"
        :table-config="tableConfig" @openViewForm="openViewForm" @openEditForm="openEditForm">
        <template v-slot:addBtn>
          <el-button type="success" @click="openCreateForm()">新增</el-button>
        </template>
      </Table>
    </div>
  </div>

  <el-dialog v-model="dialogFormVisible" :title="isRead ? '查看' : '新增'" width="860px">
    <el-form ref="queryFormRef" :model="order" class="demo-ruleForm" :rules="rules">
      <div class="dialogForm2">
        <el-form-item label="姓名：" prop="name">
          <el-input v-if="!isRead" v-model="order.name" placeholder="请输入姓名"></el-input>
          <el-text v-else>{{order.name}}</el-text>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input v-if="!isRead" v-model="order.phone" placeholder="请输入手机号"></el-input>
          <el-text v-else>{{order.phone}}</el-text>
        </el-form-item>
        <el-form-item label="认证状态：" v-if="isRead">
          <el-text>{{order.examine_name}}</el-text>
        </el-form-item>

        <el-form-item label="证件类型：" prop="uid_card_type">
          <el-select v-if="!isRead" v-model="order.uid_card_type" filterable remote reserve-keyword
            placeholder="请选择证件类型" remote-show-suffix :remote-method="remoteMethod" :loading="loading" clearable>
            <el-option v-for="item in card_list" :key="item.value" :label="item.value" :value="item.id" />
          </el-select>
          <el-text v-else>{{filterArrayById(card_list,order.uid_card_type,'id','value')}}</el-text>
        </el-form-item>
        <el-form-item label="证件号码：" prop="idcard">
          <el-input v-if="!isRead" v-model="order.idcard" placeholder="请输入证件号码"></el-input>
          <el-text v-else>{{order.idcard}}</el-text>
        </el-form-item>
      </div>
      <div style="display:flex;flex-direction: row;">
        <el-form-item label="证件照片：" prop="zcardimg">
          <el-upload class="avatar-uploader" :show-file-list="false" :http-request="e => fileUpload(e, 'zcardimg')">
            <img v-if="order.zcardimg" :src="order.zcardimg" class="avatar">
            <div class="upLoadImg" v-else>
              <img class="addImg" src="/src/assets/addIm%20g.png" alt="">
              <div class="titles">人物页上传</div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="" prop="fcardimg" style="margin-left: 6px;">
          <el-upload class="avatar-uploader" :show-file-list="false" :http-request="e => fileUpload(e, 'fcardimg')">
            <img v-if="order.fcardimg" :src="order.fcardimg" class="avatar">
            <div class="upLoadImg" v-else>
              <img class="addImg" src="/src/assets/addIm%20g.png" alt="">
              <div class="titles">国徽页上传</div>
            </div>
          </el-upload>
        </el-form-item>
      </div>
      <div class="dialogForm2">
        <el-form-item label="药师图片：" prop="quali" style="display: flex;flex-direction: row;">
          <el-upload class="avatar-uploader" :show-file-list="false" :http-request="e => fileUpload(e, 'quali')">
            <img v-if="order.quali" :src="order.quali" class="avatar">
            <div class="upLoadImg" v-else>
              <img class="addImg" src="/src/assets/addIm%20g.png" alt="">
              <div class="titles">上传图片</div>
            </div>
          </el-upload>
          <span style="width: 100px;font-size: 12px;margin-left: 6px;line-height: 1.2;">（图片格式为png，图片大小不超过50K）</span>
        </el-form-item>
        <el-form-item label="医生资格证：" prop="sdjg_avatar">
          <el-upload class="avatar-uploader" :show-file-list="false" :http-request="e => fileUpload(e, 'sdjg_avatar')">
            <img v-if="order.sdjg_avatar" :src="order.sdjg_avatar" class="avatar">
            <div class="upLoadImg" v-else>
              <img class="addImg" src="/src/assets/addIm%20g.png" alt="">
              <div class="titles">上传图片</div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="科室：" prop="department_id">
          <el-select v-if="!isRead" v-model="order.department_id" filterable remote reserve-keyword
            placeholder="请选择所属一级科室" remote-show-suffix :remote-method="remoteMethod" :loading="loading" clearable>
            <el-option v-for="item in department_list" :key="item.value" :label="item.name" :value="item.id" />
          </el-select>
          <el-text v-else>{{filterArrayById(department_list,order.department_id,'id','name')}}</el-text>
        </el-form-item>
        <el-form-item label="职称：" prop="position_id">
          <el-select v-if="!isRead" v-model="order.position_id" filterable remote reserve-keyword placeholder="请选择药师职称"
            remote-show-suffix :remote-method="remoteMethod" :loading="loading" clearable>
            <el-option v-for="item in position_list" :key="item.value" :label="item.name" :value="item.id" />
          </el-select>
          <el-text v-else>{{filterArrayById(position_list,order.position_id,'id','name')}}</el-text>
        </el-form-item>
        <el-form-item label="所属诊疗科目：" prop="subject">
          <el-select v-if="!isRead" v-model="order.subject" filterable remote reserve-keyword placeholder="请选择所属诊疗科目"
            remote-show-suffix :remote-method="remoteMethod" :loading="loading" clearable>
            <el-option v-for="item in subject_list" :key="item.value" :label="item.name" :value="item.code" />
          </el-select>
          <el-text v-else>{{filterArrayById(subject_list,order.subject,'code','name')}}</el-text>
        </el-form-item>
        <el-form-item label="关联药房：" prop="drugstore_id">
          <el-select v-if="!isRead" v-model="order.drugstore_id" multiple filterable remote reserve-keyword placeholder="请选择关联药房"
            remote-show-suffix :remote-method="remoteMethod" :loading="loading" clearable>
            <el-option v-for="item in pharmacy_list" :key="item.value" :label="item.name" :value="item.id" />
          </el-select>
          <el-text v-else>{{filterArrayById2(pharmacy_list,order.drugstore_id)}}</el-text>
        </el-form-item>
        <el-form-item label="资格证书编号：" prop="management_number">
          <el-input v-if="!isRead" v-model="order.management_number" placeholder="请输入资格证书编号"></el-input>
          <el-text v-else>{{order.management_number}}</el-text>
        </el-form-item>
        <el-form-item label="执业证书发证日期：" prop="practice_day">
          <!--  <el-input v-model="order.practice_day" placeholder="请输入执业证书发证日期"></el-input> -->
          <el-date-picker v-if="!isRead" v-model="order.practice_day" type="date" placeholder="请输入执业证书发证日期"
            format="YYYY-MM-DD" value-format="YYYY-MM-DD" :size="size" />
          <el-text v-else>{{order.practice_day}}</el-text>
        </el-form-item>
        <el-form-item label="临床工作年限：" prop="working_seniority">
          <el-input v-if="!isRead" v-model="order.working_seniority" placeholder="请输入临床工作年限"></el-input>
          <el-text v-else>{{order.working_seniority}}</el-text>
        </el-form-item>
        <el-form-item label="第一执业机构编码：" prop="one_code">
          <el-input v-if="!isRead" v-model="order.one_code" placeholder="请输入第一执业机构编码"></el-input>
          <el-text v-else>{{order.one_code}}</el-text>
        </el-form-item>
        <el-form-item label="第一执业机构名称：" prop="one_mechanism">
          <el-input v-if="!isRead" v-model="order.one_mechanism" placeholder="请输入第一执业机构名称"></el-input>
          <el-text v-else>{{order.one_mechanism}}</el-text>
        </el-form-item>
        <el-form-item label="业务类型：" prop="business_type">
          <el-select v-if="!isRead" v-model="order.business_type" filterable remote reserve-keyword
            placeholder="请选择业务类型" remote-show-suffix :remote-method="remoteMethod" :loading="loading" clearable>
            <el-option v-for="item in business_list" :key="item.value" :label="item.value" :value="item.id" />
          </el-select>
          <el-text v-else>{{filterArrayById(business_list,order.business_type,'id','value')}}</el-text>
        </el-form-item>
        <el-form-item label="民族：" prop="nation">
          <el-select v-if="!isRead" v-model="order.nation" filterable remote reserve-keyword placeholder="请选择民族"
            remote-show-suffix :remote-method="remoteMethod" :loading="loading" clearable>
            <el-option v-for="item in nation_list" :key="item.value" :label="item.name" :value="item.id" />
          </el-select>
          <el-text v-else>{{filterArrayById(nation_list,order.nation,'id','name')}}</el-text>
        </el-form-item>
      </div>
      <el-form-item>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(queryFormRef)">
            保存
          </el-button>
        </div>
      </el-form-item>
    </el-form>

  </el-dialog>
</template>

<script setup>
  const qiniuParseUrl = String(import.meta.env.VITE_QINIU_PARSE_URL)
  const emit = defineEmits(['updateForm'])
  import {
    token as qiniuTokenApi
  } from "@/api/common"
  import * as qiniu from 'qiniu-js'
  import {
    tableColumn as tableColumns,
    pageConfig,
    tableConfig
  } from './config'
  import Table from '/src/components/Table/index.vue'
  import Form from '/src/components/Form/index.vue'
  import {
    list,
    update,
    create,
    status,
    emus,
    emuspharmacy,
    showDetail
  } from '/src/api/user/pharmacist'
  import {
    ArrowDown,
    Check,
    CircleCheck,
    CirclePlus,
    CirclePlusFilled,
    Plus, Upload
  } from '@element-plus/icons-vue'
  import {
    ref,
    nextTick,
    onMounted,
    reactive
  } from 'vue'
  import {
    ElMessage
  } from "element-plus";
  const qiniuToken = ref("")
  const options = {
    quality: 1,
    noCompressIfLarger: true
  }
  const dialogFormVisible = ref(false)
  const isRead = ref(false)
  const queryFormRef = ref()
  const order = ref({})
  const loading = ref(false)
  const mechanism_list = ref([])
  const form = ref({
    status: 1
  })

  const xrForm = ref()
  const xrTable = ref()
  const tableColumn = reactive([...tableColumns])

  const rules = reactive({
    name: [{
      required: true,
      message: '姓名不能为空',
      trigger: 'submit'
    }],
    phone: [{
      required: true,
      message: '手机号不能为空',
      trigger: 'submit'
    }],
    uid_card_type: [{
      required: true,
      message: '证件类型不能为空',
      trigger: 'submit'
    }],
    idcard: [{
      required: true,
      message: '证件号不能为空',
      trigger: 'submit'
    }],
    zcardimg: [{
      required: true,
      message: '证件照不能为空',
      trigger: 'submit'
    }],
    fcardimg: [{
      required: true,
      message: '证件照不能为空',
      trigger: 'submit'
    }],
    quali: [{
      required: true,
      message: '药师照片不能为空',
      trigger: 'submit'
    }],
    sdjg_avatar: [{
      required: true,
      message: '医生资格证不能为空',
      trigger: 'submit'
    }],
    department_id: [{
      required: true,
      message: '科室不能为空',
      trigger: 'submit'
    }],
    position_id: [{
      required: true,
      message: '职称不能为空',
      trigger: 'submit'
    }],
    subject: [{
      required: true,
      message: '所属诊疗科目不能为空',
      trigger: 'submit'
    }],
    drugstore_id: [{
      required: true,
      message: '药店不能为空',
      trigger: 'submit'
    }],
    management_number: [{
      required: true,
      message: '资格证书编号不能为空',
      trigger: 'submit'
    }],
    practice_day: [{
      required: true,
      message: '发证日期不能为空',
      trigger: 'submit'
    }],
    working_seniority: [{
      required: true,
      message: '工作年限不能为空',
      trigger: 'submit'
    }],
    one_mechanism: [{
      required: true,
      message: '第一执业机构名称不能为空',
      trigger: 'submit'
    }],
    one_code: [{
      required: true,
      message: '第一执业机构编码不能为空',
      trigger: 'submit'
    }],
    business_type: [{
      required: true,
      message: '业务类型不能为空',
      trigger: 'submit'
    }],
    nation: [{
      required: true,
      message: '民族不能为空',
      trigger: 'submit'
    }]
  })

  const openCreateForm = () => {
    // queryFormRef.value.clearValidate(); // 清除验证信息
    // order.value = {}; // 清空表单数据
    isRead.value = false
    dialogFormVisible.value = true

    // nextTick(() => {
    //   form.value = {
    //     status: 1
    //   }
    //   xrForm.value.ruleFormRef.resetFields()
    //   xrForm.value.ruleFormRef.clearValidate()
    // })
  }
  const openViewForm = (row) => {
    isRead.value = true
    dialogFormVisible.value = true
    getDetail(row.id)
  }
  const getDetail = async (id) => {
    try {
      const result = await showDetail({
        id: id
      })
      console.log('详情', result)
      if (result.code == 200) {
        console.log('药师详情');
        dialogFormVisible.value = true;
        order.value = result.data; // 清空表单数据

      }
    } catch (error) {
      console.error('获取列表时出错：', error)
    }
  }
  const openEditForm = (row) => {
    isRead.value = false
    dialogFormVisible.value = true
    form.value = {
      ...row
    }
    nextTick(() => {
      xrForm.value.ruleFormRef.clearValidate()
      xrForm.value.buildFormSelData()
    })
  }

  const remoteMethod = async (query, f) => {
    for (const i in tableColumn) {
      if (tableColumn[i].prop === f.prop) {
        const options = f.selectRemoteOptions || {};
        options[f.selectRemoteKey] = query;
        const res = await f.asyncSelDataApi(options);
        f.asyncSelData = res.data
        tableColumn.splice(i, 1, f)
      }
    }
  }

  const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log('submit!')
        console.log(order.value)
        getCreate()

      } else {
        console.log(order.value)
        console.log('error submit!', fields)
      }
    })
  }

  const getCreate = async () => {
    try {
      const options = {
        ...order.value
      }
      const result = await create({
        ...options,
        drugstore_id: order.value.drugstore_id
      })
      console.log('添加药师', result)
      if (result.code == 200) {
        ElMessage('添加成功');
        dialogFormVisible.value = false;
        queryFormRef.value.clearValidate(); // 清除验证信息
        order.value = {}; // 清空表单数据
        xrTable.value.resetFormParent()

      }
    } catch (error) {
      console.error('获取列表时出错：', error)
    }
  }

  const buildFormSelData = async () => {
    for (const column of tableColumn.filter(item => item.isForm)) {
      if (column.asyncSelDataApi) {
        const res = await column.asyncSelDataApi();
        column.asyncSelData = res.data;
      }
    }
  }

  const business_list = ref([]) //业务类型
  const department_list = ref([]) //科室类型
  const position_list = ref([]) //职称类型
  const card_list = ref([]) //证件类型
  const nation_list = ref([]) //民族类型
  const subject_list = ref([])
  const pharmacy_list = ref([])

  const getEmus = async () => {
    try {
      const options = {
        class: 'doctor',
        method: 'getBusiness',
        resource: 'DoctorResource'
      }
      const result = await emus({
        ...options
      })
      console.log('业务类型下拉列表', result)
      if (result.code == 200) {
        business_list.value = result.data
      }
    } catch (error) {
      console.error('获取列表时出错：', error)
    }
  }

  const getEmus2 = async () => {
    try {
      const options = {
        class: 'department',
        method: 'getDepartment',
        resource: 'Departmentesource',
        status: "1"
      }
      const result = await emus({
        ...options
      })
      console.log('科室类型下拉列表', result)
      if (result.code == 200) {
        department_list.value = result.data
      }
    } catch (error) {
      console.error('获取列表时出错：', error)
    }
  }

  const getEmus3 = async () => {
    try {
      const options = {
        class: 'position',
        method: 'getPosition',
        resource: 'PositionResource',
        status: "1"
      }
      const result = await emus({
        ...options
      })
      console.log('科目类型下拉列表', result)
      if (result.code == 200) {
        position_list.value = result.data
      }
    } catch (error) {
      console.error('获取列表时出错：', error)
    }
  }

  const getEmus4 = async () => {
    try {
      const options = {
        class: 'doctor',
        method: 'getIdCard',
        resource: 'DoctorResource',
        status: "1"
      }
      const result = await emus({
        ...options
      })
      console.log('科目类型下拉列表', result)
      if (result.code == 200) {
        card_list.value = result.data
      }
    } catch (error) {
      console.error('获取列表时出错：', error)
    }
  }

  const getEmus5 = async () => {
    try {
      const options = {
        class: 'RecoverNation',
        method: 'getNation',
        resource: 'RecoverNationResource',
        status: "1"
      }
      const result = await emus({
        ...options
      })
      console.log('科目类型下拉列表', result)
      if (result.code == 200) {
        nation_list.value = result.data
      }
    } catch (error) {
      console.error('获取列表时出错：', error)
    }
  }
  const getEmus6 = async () => {
    try {
      const options = {
        class: 'doctor',
        method: 'getSubject',
        resource: 'SubjectResource',
        status: "1"
      }
      const result = await emus({
        ...options
      })
      console.log('科目类型下拉列表', result)
      if (result.code == 200) {
        subject_list.value = result.data
      }
    } catch (error) {
      console.error('获取列表时出错：', error)
    }
  }

  const getEmus7 = async () => {
    try {
      const options = {
        class: 'Drugstore',
        method: 'getDrugstore',
        resource: 'DrugstoreResource',
        status: "1"
      }
      const result = await emuspharmacy({
        ...options
      })
      console.log('科目类型下拉列表', result)
      if (result.code == 200) {
        pharmacy_list.value = result.data
      }
    } catch (error) {
      console.error('获取列表时出错：', error)
    }
  }

  onMounted(async () => {
    try {
      const promises = [
        getEmus(),
        getEmus2(),
        getEmus3(),
        getEmus4(),
        getEmus5(),
        getEmus6(),
        getEmus7(),
      ]
      getQiniuToken()
      const data = await Promise.all(promises)
      console.log(1111, data)
      // results.value = data
      // await buildFormSelData();
    } catch (error) {
      console.error('Error fetching data:', error)
    } finally {
      loading.value = false
    }
  })


  const getQiniuToken = async () => {
    const res = await qiniuTokenApi()
    qiniuToken.value = res.data.upToken
  }
  const getRiskSpreadRef = ref([])

  const fileUpload = (e, prop) => {
    console.log(e)
    const file = e.file;
    if (!file) return;

    const fileName = file.name; // 获取文件名
    const fileExtension = fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2); // 提取文件扩展名

    qiniu.compressImage(e.file, options).then(data => {
      const key = `images/${prop}/${new Date().getTime()}.${fileExtension}`;
      const config = {}
      const putExtra = {}
      const observer = {
        next(res) {
          // 上传过程中的状态信息
          console.log(res.total.percent);
        },
        error(err) {
          console.log(err);
        },
        complete(res) {

          console.log('qiniuParseUrl', qiniuParseUrl, prop)
          order.value[prop] = qiniuParseUrl + "/" + key
          console.log(drugInfo.value)

        }
      }
      const observable = qiniu.upload(data.dist, key, qiniuToken.value, putExtra, config)
      const subscription = observable.subscribe(observer)
    })
  }

  //筛选
  const filterArrayById = (arr, id,idName,text) => {
    const filteredItem = arr.find(item => item[idName] == id);
    return filteredItem ? filteredItem[text] : null;
  }
  // const filterArrayById2 = (arr, ids, idName, text) => {
  //   const filteredItems = arr.filter(item => ids.includes(item.id));
  //   const concatenatedValues = filteredItems.map(item => item.name).join(', ');
  //   return concatenatedValues;
  // };
  const filterArrayById2 = (arr, ids, idName, text) => {
    if (!Array.isArray(ids) || ids.length === 0) {
      return '';
    }
  
    const filteredItems = arr.filter(item => ids.includes(item.id));
    const concatenatedValues = filteredItems.map(item => item.name).join(', ');
    return concatenatedValues;
  };

  // const filterArrayById2 = (arr, id) => {
  //   const filteredItem = arr.find(item => item.id == id);
  //   return filteredItem ? filteredItem.name : null;
  // }
</script>

<style lang="scss" scoped>
  .dialogForm2 {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .dialogForm2 ::v-deep .el-form-item {
    width: 50% !important;
    margin-right: 0;
  }

  ::v-deep .el-form-item__label {
    color: #606266;
    font-weight: bold;
    width: 160px;
  }

  ::v-deep .el-select {
    width: 100% !important;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar-uploader img {
    width: 120px;
    height: auto;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  //上传的样式
  .upLoadImg {
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    padding: 6px 8px;
    text-align: center;
    width: 120px;

    .titles {
      font-size: 12px;
      color: #8c939d;
    }

    .addImg {
      width: 40px;
      height: 40px;
    }
  }

  .smTip {
    color: #e02020;
    font-size: 12px;
    margin-left: 12px;
  }

  ::v-deep .el-input::placeholder {
    color: #b6bcc4;
    font-size: 12px;
  }

  .dialog-footer {
    display: flex;
    width: 100%;
    justify-content: center;
  }
</style>